﻿using LeSoft.Util;
using LeSoft.Application.Bussiness;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using Newtonsoft.Json;
using System.IO;
using System.Collections;
namespace LeSoft.Application.Web.Areas.PropertyManage.Controllers
{
    public class CS_DeviceMaintanenceBillController : MvcControllerBase
    {

        // GET: /WorkManage/WeekBill/
        private WeekBillBLL WeekBillbll = new WeekBillBLL();
        private WorkBLL workbll = new WorkBLL();

        private static HttpFileCollection hfc;
        #region 视图
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Form()
        {
            ViewBag.Mode = new CodeRuleBLL().CheckBillCodeMode(((int)CodeRuleEnum.MaintanenceBill).ToString());
            return View();
        }
        
        #endregion

        #region 获取数据
        /// <summary>
        /// 获取工单内容详情
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <returns>工单</returns>
        public ActionResult GetWeekBillContentDetail(string keyValue)
        {
            var data = new WorkBLL().GetWorkItemEntity(keyValue);
            return Content(data.ToJson());
        }
        /// <summary>
        /// 获取工单应用设备
        /// </summary>
        /// <param name="keyValue">工单主键</param>
        /// <returns>应用设备集合</returns>
        public ActionResult GetDeviceListByWeekBillList(string keyValue)
        {
            var data = new DeviceBLL().GetList().ToList();
            var dd = new DeviceBLL().GetRelationDeviceItemList(2, null).ToList();
            dd = dd.Where(e => e.ItemId == keyValue).ToList();
            string Level = "";
            string Type = "";
            //string Project = "";
            foreach (var item in dd)
            {
                if (!Level.Contains(item.DeviceLevel))
                {
                    Level += item.DeviceLevel + ",";
                }
                if (!Type.Contains(item.DeviceTypeId))
                {
                    Type += item.DeviceTypeId + ",";
                }
                //if (!Project.Contains(item.ProjectType))
                //{
                //    Project += item.ProjectType + ",";
                //} 
            }
            if (Level != "")
            {
                data = data.Where(e => Level.Contains(e.Level)).ToList();
            }
            if (Type != "")
            {
                data = data.Where(e => Type.Contains(e.Type)).ToList();
            }
            //if (Project != "")
            //{
            //    data = data.Where(e => Project.Contains(e.)).ToList();
            //}
            var query = from a in data
                        select new
                        {
                            Id = a.Id,
                            Code = a.Code,
                            IsComplete = "<input name='IsComplete' type='checkbox' class=' CS_2 ' />完成",
                            Type = new DeviceTypeBLL().GetEntity(a.Type).IsEmpty() ? "--" : new DeviceTypeBLL().GetEntity(a.Type).Name,
                            Name = a.Name,
                            ModelNo = a.ModelNo
                        };
            if (dd.Count() == 0)
            {
                query = null;
            }
            return Content(query.ToJson());
        }

        /// <summary>
        /// 获取计划工单实体集合
        /// </summary>
        /// <param name="queryjson">过滤条件</param>
        /// <returns>工单实体集合</returns>
        public ActionResult GetWeekBillListToJson(string queryjson)
        {
            var data = WeekBillbll.GetWeekBillEntityList(queryjson);
            return Content(data.ToJson());
        }
        /// <summary>
        /// 获取计划看板信息集合
        /// </summary>
        /// <param name="queryjson"></param>
        /// <returns></returns>
        public ActionResult GetWeekBillListToJsonByTime(string queryjson)
        {
            var data = WeekBillbll.GetWeekBillEntityList("");
            var queryParam = queryjson.ToJObject();
            string ItemId = queryParam["ItemId"].ToString();
            string Week = queryParam["Week"].ToString();
            int week = 1;
            string Type = queryParam["Type"].ToString();
            int Count = Convert.ToInt32(queryParam["Count"]);
            int Year = Convert.ToInt32(queryParam["Year"]);
            DateTime BeginTime = new DateTime(Year, 1, 1);
            DateTime EndTime = new DateTime(Year, 1, 1);
            data = data.Where(e => e.ItemId == ItemId).ToList();
            if (Type == "3")
            {
                week = Convert.ToInt32(Week);
                BeginTime = BeginTime.AddDays(7 * week - 7 + Count);
                EndTime = BeginTime.AddDays(1);
                data = data.Where(e => e.BeginDate <= BeginTime && e.EndDate >= EndTime).ToList();
                return Content(data.ToJson());
            }
            else
            {
                week = Convert.ToInt32(Week.Substring(1));
                BeginTime = BeginTime.AddDays(7 * week - 7);
                EndTime = BeginTime.AddDays(7);
            }
            data = data.Where(e => (e.BeginDate >= BeginTime && e.BeginDate < EndTime) || (e.EndDate > BeginTime && e.EndDate <= EndTime) || (e.BeginDate < EndTime && e.EndDate > EndTime) || (e.BeginDate >= BeginTime && e.EndDate <= EndTime)).ToList();


            return Content(data.ToJson());

        }

        public ActionResult GetWeekBillEntityByTime(string queryjson)
        {
            var data = WeekBillbll.GetWeekBillEntityList("");
            var queryParam = queryjson.ToJObject();
            string ItemId = queryParam["ItemId"].ToString();
            string Week = queryParam["Week"].ToString();
            int week = 1;
            string Type = queryParam["Type"].ToString();
            int Count = Convert.ToInt32(queryParam["Count"]);
            int Year = Convert.ToInt32(queryParam["Year"]);
            DateTime BeginTime = new DateTime(Year, 1, 1);
            DateTime EndTime = new DateTime(Year, 1, 1);
            data = data.Where(e => e.ItemId == ItemId).ToList();
            if (Type == "3")
            {
                week = Convert.ToInt32(Week);
                BeginTime = BeginTime.AddDays(7 * week - 7 + Count);
                EndTime = BeginTime.AddDays(1);
                WeekBillEntity entity1 = data.Where(e => e.BeginDate <= BeginTime && e.EndDate >= EndTime).FirstOrDefault();
                var WorkCode1 = new WorkBLL().GetWorkItemEntity(entity1.ItemId) == null ? "" : new WorkBLL().GetWorkItemEntity(entity1.ItemId).Code;
                var WorkMemo1 = new WorkBLL().GetWorkItemEntity(entity1.ItemId) == null ? "" : new WorkBLL().GetWorkItemEntity(entity1.ItemId).Content;
                var file1 = new AttachFileBLL().GetList(entity1.Id).ToList();
                var query1 = new
                {
                    data1 = entity1,
                    data2 = WorkCode1,
                    data3 = WorkMemo1,
                    data4 = file1
                };

                return Content(query1.ToJson());
            }
            else
            {
                week = Convert.ToInt32(Week.Substring(1));
                BeginTime = BeginTime.AddDays(7 * week - 7);
                EndTime = BeginTime.AddDays(7);
            }
            WeekBillEntity entity = data.Where(e => (e.BeginDate >= BeginTime && e.BeginDate < EndTime) || (e.EndDate > BeginTime && e.EndDate <= EndTime) || (e.BeginDate < EndTime && e.EndDate > EndTime) || (e.BeginDate >= BeginTime && e.EndDate <= EndTime)).FirstOrDefault();
            var WorkCode = new WorkBLL().GetWorkItemEntity(entity.ItemId) == null ? "" : new WorkBLL().GetWorkItemEntity(entity.ItemId).Code;
            var WorkMemo = new WorkBLL().GetWorkItemEntity(entity.ItemId) == null ? "" : new WorkBLL().GetWorkItemEntity(entity.ItemId).Content;
            var file = new AttachFileBLL().GetList(entity.Id).ToList();
            var query = new
            {
                data1 = entity,
                data2 = WorkCode,
                data3 = WorkMemo,
                data4 = file
            };

            return Content(query.ToJson());
        }
        /// <summary>
        /// 获取计划工单实体
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <returns>工单实体对象</returns>
        public ActionResult GetWeekBillEntity(string keyValue)
        {
            var data = WeekBillbll.GetWeekBillEntity(keyValue);
            var WorkCode = new WorkBLL().GetWorkItemEntity(data.ItemId) == null ? "" : new WorkBLL().GetWorkItemEntity(data.ItemId).Code;
            var WorkMemo = new WorkBLL().GetWorkItemEntity(data.ItemId) == null ? "" : new WorkBLL().GetWorkItemEntity(data.ItemId).Content;
            var file = new AttachFileBLL().GetList(keyValue).ToList();
            var query = new
            {
                data1 = data,
                data2 = WorkCode,
                data3 = WorkMemo,
                data4 = file
            };

            return Content(query.ToJson());
        }

        /// <summary>
        /// 根据组织机构获取工作项目集合
        /// </summary>
        /// <param name="keyValue">组织机构Id</param>
        /// <returns></returns>
        public ActionResult GetWorkItemListByOrganizeId(string keyValue)
        {
            var data = new WorkBLL().GetWorkItemList().ToList();
            data = data.Where(e => e.OrganizeId == keyValue).ToList();
            foreach (var item in data)
            {
                item.Type = new WorkBLL().GetWorkTypeEntity(item.Type).IsEmpty() ? "" : new WorkBLL().GetWorkTypeEntity(item.Type).Name;
            }
            return Content(data.ToJson());
        }
        #endregion

        #region 操作
        /// <summary>
        /// 保存计划工单
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <param name="entity">工单实体</param>
        /// <returns></returns>
        public ActionResult SaveWeekBillForm(string keyValue, WeekBillEntity entity)
        {

            try
            {
                WeekBillbll.SaveWeekBillEntity(keyValue, entity);//保存工单实体
                var s = entity.Id;
                entity.EnabledMark = 1;
                List<AttachFileEntity> lst = GetAttachFileEntityLsit();
                if (lst.Count() != 0)
                {
                    foreach (var item in lst)
                    {
                        item.BillId = s;
                        new AttachFileBLL().SaveForm(item); //保存图片实体
                    }
                }
                return Success("操作成功");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }

        }
        /// <summary>
        /// 删除计划工单
        /// </summary>
        /// <param name="keyValue">主键值</param>
        /// <returns></returns>
        public ActionResult RemoveWeekBillForm(string keyValue)
        {
            try
            {
                WeekBillbll.RemoveWeekBillEntity(keyValue);
                return Success("操作成功");
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }

        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        public ActionResult UploadFile()
        {
            hfc = System.Web.HttpContext.Current.Request.Files;
            return Success("操作成功。");
        }
        /// <summary>
        /// 获取上传图片实体集合
        /// </summary>
        /// <returns></returns>
        public List<AttachFileEntity> GetAttachFileEntityLsit()
        {
            List<AttachFileEntity> listFile = new List<AttachFileEntity>();

            string URL = Request.Url.ToString().Replace(Request.RawUrl, "/");
            // string URL = Config.GetValue("FileUrl");
            string imgPath = "/Resource/WeekBillFile_" + OperatorProvider.Provider.Current().CustomerCode + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
            if (hfc != null && hfc.Count > 0)
            {
                for (int i = 0; i < hfc.Count; i++)
                {
                    if (hfc[i].FileName == "") continue;
                    else
                    {
                        AttachFileEntity AttachFileEntity = new AttachFileEntity();
                        AttachFileEntity.Create();
                        AttachFileEntity.Category = 2;
                        AttachFileEntity.Type = 21;
                        AttachFileEntity.TypeName = "计划工单附件";
                        AttachFileEntity.FileName = hfc[i].FileName;
                        string FilePath = Server.MapPath(imgPath);
                        if (!Directory.Exists(FilePath))
                        {
                            Directory.CreateDirectory(FilePath);
                        }
                        hfc[i].SaveAs(FilePath + hfc[i].FileName);
                        AttachFileEntity.FileUrl = FilePath.Replace(HttpRuntime.AppDomainAppPath, URL) + hfc[i].FileName;
                        listFile.Add(AttachFileEntity);
                    }
                }
            }
            return listFile;
        }


        #endregion


        #region 看板
      

     

      

        public ActionResult GetWeekBillList(Pagination pagination, string queryJson)
        {
            var data = WeekBillbll.GetPageList(pagination, queryJson);
            var watch = CommonHelper.TimerStart();
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }


      
      

      
       
        #endregion
       
    }
}
